package org.changs.aplug;

import android.app.Activity;
import android.support.annotation.Nullable;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;


public final class ActivityManager  {

    private final static ActivityManager instance = new ActivityManager();

    private Stack<Activity> activityStack = new Stack<>();

    private ActivityManager() {
    }

    public static ActivityManager getInstance() {
        return instance;
    }
    public void onActivityCreated(Activity activity) {
        activityStack.add(activity);
    }

    public void onActivityDestroyed(Activity activity) {
        activityStack.remove(activity);
    }


    /**
     * 获取当前Activity（堆栈中最后一个压入的）
     */
    @Nullable
    public Activity getCurrentActivity() {
        if (activityStack.size() == 0) return null;
        return activityStack.get(activityStack.size() - 1);
    }

    public Activity getPreActivity() {
        int size = activityStack.size();
        if (size < 2) return null;
        return activityStack.get(size - 2);
    }

    /**
     * 获取当前 Activity 之前所有 Activity
     *
     * @return
     */
    public List<Activity> getPreActivies() {
        List<Activity> preActivities = new ArrayList<>();
        for (int i = 0, size = activityStack.size(); i < size; i++) {
            if (activityStack.get(i) == getCurrentActivity()) {
                break;
            }
            preActivities.add(activityStack.get(i));
        }
        return preActivities;
    }

    /**
     * 结束当前Activity（堆栈中最后一个压入的）
     */
    public void finishActivity() {
        Activity activity = activityStack.get(activityStack.size() - 1);
        finishActivity(activity);
    }

    /**
     * 结束指定的Activity
     */
    public void finishActivity(Activity activity) {
        if (activity != null) {
            activityStack.remove(activity);
            activity.finish();
        }
    }

    /**
     * 结束指定的Activity
     */
    public void finishActivity(Class<? extends Activity> clazz) {
        finishActivity(findActivity(clazz));
    }

    /**
     * 结束所有Activity
     */
    public void finishAllActivity() {
        for (int i = 0, size = activityStack.size(); i < size; i++) {
            if (null != activityStack.get(i)) {
                Activity activity = activityStack.get(i);
                if (!activity.isFinishing()) {
                    activity.finish();
                }
            }
        }
        activityStack.clear();
    }

    @SuppressWarnings("unchecked")
    public <T extends Activity> T findActivity(Class<T> clazz) {
        for (Activity activity : activityStack) {
            if (activity.getClass() == clazz)
                return (T) activity;
        }
        return null;
    }
}
